import os
import random
import math
import time

import cv2 as cv
import numpy as np
import multiprocessing
import creater.creatorMain

width = 1024
height = 1280


def calculate_circle_ring_center(center_circle_p_, center_circle_rs_, single_circle_r_):
    single_center_p = []
    center_single_r = center_circle_rs_ - single_circle_r_
    # 计算六个圆的圆心的中心点的位置
    p1 = [center_circle_p_[0] - center_single_r, center_circle_p_[1]]
    p2 = [center_circle_p_[0] + center_single_r, center_circle_p_[1]]
    p3 = [center_circle_p_[0] - center_single_r * math.sin(math.radians(30)), center_circle_p_[1] + center_single_r *
          math.cos(math.radians(30))]
    p4 = [center_circle_p_[0] + center_single_r * math.sin(math.radians(30)), center_circle_p_[1] + center_single_r *
          math.cos(math.radians(30))]
    p5 = [center_circle_p_[0] - center_single_r * math.sin(math.radians(30)), center_circle_p_[1] - center_single_r *
          math.cos(math.radians(30))]
    p6 = [center_circle_p_[0] + center_single_r * math.sin(math.radians(30)), center_circle_p_[1] - center_single_r *
          math.cos(math.radians(30))]
    single_center_p.append(p1)
    single_center_p.append(p2)
    single_center_p.append(p3)
    single_center_p.append(p4)
    single_center_p.append(p5)
    single_center_p.append(p6)
    return single_center_p


def add_salt_and_pepper_noise(image, noise_ratio):
    noisy_pixels = int(noise_ratio * image.size)
    for _ in range(noisy_pixels):
        row = np.random.randint(0, image.shape[0])
        col = np.random.randint(0, image.shape[1])
        if np.random.rand() < 0.5:
            image[row, col] = 0  # 设置为黑色
        else:
            image[row, col] = 255  # 设置为白色


def point_to_center_dis(point, center_):
    return math.sqrt(math.pow((point[0] - center_[0]), 2) + math.pow((point[1] - center_[1]), 2))


def add_noise(img, xminp, xmaxp, yminp, ymaxp, center, radius, noise_random):
    for ii in range(xminp, xmaxp):
        for jj in range(yminp, ymaxp):
            point_ = [ii, jj]
            if point_to_center_dis(point_, center) <= radius+2:
                if np.random.rand() < noise_random:
                    # img[jj, ii] = random.randint(50, 87)
                    if np.random.rand() < 0.5:
                        img[jj, ii] = random.randint(0, 100)
                    else:
                        img[jj, ii] = random.randint(130, 255)
                    # if np.random.rand() < 0.5:
                    #     img[jj, ii] = 0  # 设置为黑色
                    # else:
                    #     img[jj, ii] = 180  # 设置为白色


def create_img_by_img():
    # 读取原始图像并转换为灰度图像
    image = cv.imread('/home/mikoptik/yolov7_test/yolo_v7/realData/23.05.26/circlesring/34.bmp', cv.IMREAD_GRAYSCALE)
    # 获取原始图像的灰度值分布直方图
    hist = cv.calcHist([image], [0], None, [256], [0, 256])
    # 计算累积直方图
    cdf = hist.cumsum()
    # 归一化累积直方图
    cdf_normalized = cdf / cdf.max()
    # 生成随机数列
    random_values = np.random.rand(image.shape[0] * image.shape[1])
    # 根据灰度值分布对随机数列进行排序
    sorted_values = np.interp(random_values, cdf_normalized, np.arange(0, 256))
    # 将排序后的值重塑为与原始图像相同大小的矩阵
    sorted_image = np.reshape(sorted_values, image.shape).astype(np.uint8)
    return sorted_image


def wirite_img(center_circle_ps, center_circle_rs, single_circle_rs, txt_biaozhu_file_, bmp_paths, j_):
    single_center_p = calculate_circle_ring_center(center_circle_ps, center_circle_rs, single_circle_rs)
    # color = 40 if np.random.rand() < 0.7 else 230
    color = random.randint(30, 40)
    random_array = np.random.randint(0, 256, size=(width, height), dtype=np.uint8)
    img = np.where(random_array < 128, 0, random_array)
    # img = create_img_by_img()
    # 在生成的图片的基础上添加圆形
    for iss in range(len(single_center_p)):
        index = iss % len(single_center_p)
        single = single_center_p[index]

        centerx = (single[0]) / height
        centery = (single[1]) / width
        dx = (2 * single_circle_rs) / height
        dy = (2 * single_circle_rs) / width
        cv.circle(img, (int(single[0]), int(single[1])), single_circle_rs, color, -1, cv.LINE_AA)

        xminp = int(single[0] - single_circle_rs)
        yminp = int(single[1] - single_circle_rs)
        xmaxp = int(single[0] + single_circle_rs)
        ymaxp = int(single[1] + single_circle_rs)

        noise_random = 0.3
        add_noise(img, xminp, xmaxp, yminp, ymaxp, single, single_circle_rs, noise_random)
        # cv.rectangle(img, (xminp, yminp), (xmaxp, ymaxp), 255, 5)

        # txt_file_.write("name: " + str(j_) + '.bmp')
        # txt_file_.write("    center_point: " + str(single[0]) + "," + str(single[1]))
        # txt_file_.write("    radius: " + str(single_circle_rs) + "\n")

        txt_biaozhu_file_.write("0" + ' ')
        txt_biaozhu_file_.write(str(centerx) + ' ')
        txt_biaozhu_file_.write(str(centery) + ' ')
        txt_biaozhu_file_.write(str(dx) + ' ')
        txt_biaozhu_file_.write(str(dy) + ' ' + "\n")
        # 用于测试的外圆
        # cv.circle(img, (center_circle_ps[0], center_circle_ps[1]), center_circle_rs + 10, color, 2, cv.LINE_AA)
    ksize = (3, 3)
    sigma = 0
    # add_salt_and_pepper_noise(img, 0.3)
    blurred = cv.GaussianBlur(img, ksize, sigma)
    cv.imwrite(bmp_paths, blurred)


def rand_center(radius):
    x = random.randint(radius, width - 2 * radius)
    y = random.randint(radius, height - 2 * radius)
    return [y, x]


if __name__ == '__main__':

    root_dir = "/home/mikoptik/yolov7_test/yolo_v7/match_circle"  # 生成图片存放的路径match_circle
    dir_num = 1
    img_num = 10000

    for i in range(1, dir_num + 1):
        each_dir_path = os.path.join(root_dir, str(i))
        biaozhu_res_path = os.path.join(each_dir_path, "res")
        # txt_path = os.path.join(each_dir_path, str(i) + ".txt")
        print(i, "dir begin, each nums-->", img_num)
        if not os.path.exists(each_dir_path):
            os.makedirs(each_dir_path)
        if not os.path.exists(biaozhu_res_path):
            os.makedirs(biaozhu_res_path)
        # txt_file = open(txt_path, 'w')
        # pool = multiprocessing.Pool()
        # pool.map()
        for j in range(1, img_num + 1):
            statr_time = time.time()
            center_circle_r = random.randint(75, 120)  # 包裹六个圆的大圆的半径
            single_circle_r = random.randint(18, 25)  # 每个小圆的半径
            center_circle_p = rand_center(center_circle_r)  # 圆环阵的中心点
            bmp_path = os.path.join(each_dir_path, "rcn"+str(j) + '.bmp')
            txt_biaozhu_res = os.path.join(biaozhu_res_path, "rcn"+str(j) + ".txt")
            txt_biaozhu_file = open(txt_biaozhu_res, 'w')
            wirite_img(center_circle_p, center_circle_r, single_circle_r, txt_biaozhu_file, bmp_path, j)
            end_time = time.time()
            if j % 100 == 0:
                print(j, "--> img finish", "time-->", end_time - statr_time)
        print(i, "dir finish, path loop-->", each_dir_path)
    print("all image finish, total nums-->", dir_num * img_num)


